""" 

    Pledges.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which determines if a user has/has not pledged
    to support transparency in government and returns the data as a JSON object.

    Accepts one parameters:
        ids (required) - comma delimited list of Bioguide Ids
    
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import string

from sets import Set
from django.utils import simplejson
from facebook import FacebookError
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from utils import fbUtil, dbUtil, Pledges

class MainHandler(webapp.RequestHandler):
    
    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "pledges":[]}
        
        try:
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, False)
            if self.facebookapi is None:
                jsonOutput["result"] = "error"
                jsonOutput["message"] = "not logged in"
            else:
                
                theIds = self.request.get('ids', default_value=None)
                uid = int(self.facebookapi.uid)
                
                if theIds is not None:  
                    
                    myPledge = Pledges.get_or_insert("user"+str(uid), uid=uid, type="user")
                    if myPledge.count == 0:
                        jsonOutput["canPledge"] = True
                    else:
                        jsonOutput["canPledge"] = False
                            
                    legislatorIds = theIds.split(",")       
                    for legislatorId in legislatorIds:
                        newPledge = Pledges.get_or_insert("legislator"+str(legislatorId), legislator=legislatorId, type="legislator")                  
                        if legislatorId != "TOTAL":
                            jsonOutput["pledges"].append({"name":const.FRIENDLY_NAME[newPledge.legislator], "count": newPledge.count})    
                        else:
                            jsonOutput["total"] = newPledge.count
                                
                else:
                    jsonOutput["result"] = "error"
                    jsonOutput["message"] = "missing parameters"  
                        
            
        except FacebookError, e:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = str(e.msg)
                       
        self.response.out.write(simplejson.dumps(jsonOutput))          
  
def main():
	application = webapp.WSGIApplication([('/fb/pledges', MainHandler)],
									   debug=True)
	run_wsgi_app(application)


if __name__ == '__main__':
	main()
